<template>
  <div class="manus-app">
    <div class="back-button" @click="goBack">
      <svg viewBox="0 0 24 24" fill="currentColor">
        <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
      </svg>
      返回主页
    </div>

    <ChatRoom
      ref="chatRoom"
      title="AI 超级智能体"
      :chat-id="chatId"
      @send-message="handleSendMessage"
    />
  </div>
</template>

<script>
import ChatRoom from '../components/ChatRoom.vue'
import apiClient from '../utils/api.js'

export default {
  name: 'ManusApp',
  components: {
    ChatRoom
  },
  data() {
    return {
      chatId: '',
      eventSource: null,
      isConnecting: false
    }
  },
  methods: {
    /**
     * 返回主页
     */
    goBack() {
      // 关闭EventSource连接
      if (this.eventSource) {
        this.eventSource.close()
      }
      this.$router.push('/')
    },

    /**
     * 生成聊天室ID
     */
    generateChatId() {
      const timestamp = Date.now()
      const random = Math.random().toString(36).substr(2, 9)
      return `manus_${timestamp}_${random}`
    },

    /**
     * 处理发送消息
     */
    async handleSendMessage(message) {
      // 防止重复请求
      if (this.isConnecting) {
        console.log('正在连接中，忽略重复请求')
        return
      }

      try {
        this.isConnecting = true
        this.$refs.chatRoom.setLoading(true)

        // 关闭之前的连接
        if (this.eventSource) {
          this.eventSource.close()
          this.eventSource = null
        }

        // 构建请求URL
        const url = `/ai/manus/chat?message=${encodeURIComponent(message)}`

        console.log('发起Manus请求:', url)

        // 先创建一个空的AI消息气泡
        this.$refs.chatRoom.startNewAIMessage()

        // 创建EventSource连接
        const fullUrl = `${apiClient.defaults.baseURL}${url}`
        this.eventSource = new EventSource(fullUrl)

        this.eventSource.onopen = (event) => {
          console.log('Manus SSE连接已建立')
          this.$refs.chatRoom.setTyping(true)
          this.isConnecting = false
        }

        this.eventSource.onmessage = (event) => {
          console.log('收到Manus AI回复:', event.data)
          this.$refs.chatRoom.setTyping(false)

          try {
            // 处理接收到的数据
            if (event.data && event.data.trim()) {
              let content = event.data

              // 检查是否是结束标志
              if (content === '[DONE]' || content === 'data: [DONE]') {
                this.$refs.chatRoom.completeCurrentAIMessage()
                this.$refs.chatRoom.setLoading(false)
                this.eventSource.close()
                return
              }

              // 处理data:前缀
              if (content.startsWith('data: ')) {
                content = content.substring(6)
              }

              // 如果是JSON格式，尝试解析
              try {
                const parsed = JSON.parse(content)
                content = parsed.content || parsed.message || parsed.data || content
              } catch (e) {
                // 如果不是JSON，直接使用原始数据
              }

              // 累积更新AI消息
              if (content && content.trim()) {
                this.$refs.chatRoom.addAIMessage(content, false)
              }
            }
          } catch (error) {
            console.error('处理Manus消息时出错:', error)
          }
        }

        this.eventSource.onerror = (event) => {
          console.error('Manus SSE连接错误:', event)
          this.isConnecting = false
          this.$refs.chatRoom.setLoading(false)
          this.$refs.chatRoom.setTyping(false)

          // 只有在没有正常消息的情况下才显示错误
          const lastMessage = this.$refs.chatRoom.messages[this.$refs.chatRoom.messages.length - 1]
          if (!lastMessage || lastMessage.content.trim() === '') {
            this.$refs.chatRoom.addAIMessage('抱歉，连接出现问题，请稍后重试。', true)
          } else {
            this.$refs.chatRoom.completeCurrentAIMessage()
          }

          if (this.eventSource) {
            this.eventSource.close()
          }
        }

      } catch (error) {
        console.error('发送Manus消息失败:', error)
        this.isConnecting = false
        this.$refs.chatRoom.setLoading(false)
        this.$refs.chatRoom.setTyping(false)
        this.$refs.chatRoom.addAIMessage('抱歉，发送消息时出现错误，请稍后重试。', true)
      }
    }
  },

  created() {
    // 生成聊天室ID
    this.chatId = this.generateChatId()
    console.log('生成Manus聊天室ID:', this.chatId)
  },

  beforeUnmount() {
    // 组件销毁前关闭EventSource连接
    if (this.eventSource) {
      this.eventSource.close()
    }
  }
}
</script>

<style scoped>
.manus-app {
  height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #4834d4, #686de0);
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  padding: 10px 16px;
  border-radius: 25px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.back-button:hover {
  background: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.back-button svg {
  width: 18px;
  height: 18px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .back-button {
    top: 15px;
    left: 15px;
    padding: 8px 12px;
    font-size: 13px;
  }

  .back-button svg {
    width: 16px;
    height: 16px;
  }
}
</style>
